<?php

namespace app\admin\model;

use app\admin\model\InsuranceUser;
use app\common\constants\MenuConstant;
use app\common\model\TimeModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
// use think\crypt\Crypt;
use app\common\utils\Crypt;

use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

class InsurancePolicy extends TimeModel
{

    public function user(): BelongsTo
    {
        return $this->belongsTo(InsuranceUser::class, 'user_id', 'id');
    }

    public function report(): HasOne{
        return $this->hasOne(InsuranceReport::class,'policy_id','id');
    }

    protected function getOptions(): array
    {
        return [
            'deleteTime' => 'delete_time',
        ];
    }

    protected $type = [
        // 'start_at_sy'  =>  'timestamp',
        // 'ocr_json_sy' => 'json',
    ];

    public function setStartAtAttr($value){
        return empty($value) ? $value : strtotime($value);
    }

    public function getStartAtAttr($value){
        return empty($value) ? $value : date('Y-m-d H:i:s', $value);
    }

    public function setEndAtAttr($value){
        return empty($value) ? $value : strtotime($value);
    }

    public function getEndAtAttr($value){
        return empty($value) ? $value : date('Y-m-d H:i:s', $value);
    }

    public function setCreateAtAttr($value){
        if (empty($value)) return $value;
        if (is_numeric($value)) return $value;
        return strtotime($value);
    }

    public function getCreateAtAttr($value){
        return empty($value) ? $value : date('Y-m-d', $value);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public static function getList(): array
    {
        $field = 'id,insurer,carno';
        $list = self::field($field)->where([
            ['status', '=', 1],
        ])->select()->toArray();

        return $list;
    }

    public function scopeRe($query, $re)
    {
    	$query->whereBetween('end_at', $re)->where('status', 1)->field('*');
    }

}